#coding=utf-8
from flask import Flask, request

from flask_sqlalchemy import SQLAlchemy

import json
import time

'''info = {
    'ip': request.remote_addr,
    'args': request.args,
    'form': request.form,
    'files': request.files,
    'headers': dict(request.headers),
    'cookies': request.cookies,
    'method': request.method,
    'path': request.path,
    'url': request.url,
    'json': request.json,
    'data': request.data.decode('utf-8') if request.data else None
}
'''

app = Flask(__name__)

# username：MySQL 用户名。
# password：MySQL 密码。
# localhost：MySQL 主机地址（本地通常为 localhost）。
# dbname：数据库名称。


# 'mysql+pymysql://game:4LWkeKK5MW8D3zpp@localhost/game'
# 'mysql+pymysql://game:4LWkeKK5MW8D3zpp@114.132.49.160:3306/game'
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://game:4LWkeKK5MW8D3zpp@localhost/game'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False #决定是否追踪对象的修改并发送信号
db = SQLAlchemy(app)


class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    servername = db.Column(db.String(30)) #unique=True, nullable=False
    name = db.Column(db.String(50))
    zhixing = db.Column(db.String(50))
    caozuo = db.Column(db.String(120))
    param1 = db.Column(db.String(120))
    param2 = db.Column(db.String(120))
    timestr = db.Column(db.String(80))


    def __repr__(self):
        return '<User %r>' % self.username


class Czrank(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    servername = db.Column(db.String(30))
    name = db.Column(db.String(50))
    job = db.Column(db.String(10))
    sex = db.Column(db.String(10))
    cz = db.Column(db.Integer)
    userid = db.Column(db.String(50))

with app.app_context():
    db.create_all()


@app.route("/")
def index():
    data = Czrank.query.order_by(Czrank.cz.desc()).all()
    # 使用HTML标签返回页面
    html_content = '''<style>table {border-collapse: collapse;width: 80%;margin: 20px auto;}\
th, td {padding: 6px;text-align: left;border-bottom: 1px solid #ddd;}\
th {background-color: #f2f2f2;font-weight: bold;}\
tr:hover {background-color: #f5f5f5;}\
td:nth-child(6) {text-align: right;padding-right: 20px;}</style>'''
    html_content += '<h2 style="text-align:center">充值排行数据</h2>'
    html_content += '<table border="1">'
    html_content += '<tr><th>ID</th><th>服务器名</th><th>姓名</th><th>职业</th><th>性别</th><th>充值</th></tr>'
    num = 1
    for row in data:
        html_content += f'<tr><td>{num}</td><td>{row.servername}</td><td>{row.name}</td><td>{row.job}</td><td>{row.sex}</td><td>{row.cz}</td></tr>'
        num += 1
    html_content += '</table>'
    
    return html_content


@app.route("/get996gjmm")
def get996gjmm():
    return "ganjindouQ2659872875"

@app.route("/postgmdata", methods=['POST'])
def postgmdata():

    data = request.data.decode('utf-8') if request.data else None
    if not data:
        return ""
    data = json.loads(data)

    servername = data.get("servername", "")
    name = data.get("name", "")
    zhixing = data.get("zhixing", "")
    caozuo = data.get("caozuo", "")
    param1 = data.get("param1", "")
    param2 = data.get("param2", "")
    timestr = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    if caozuo :
        user = User(servername=servername, name=name,zhixing=zhixing, caozuo=caozuo, param1=param1, param2=param2, timestr=timestr)
        try:
            db.session.add(user)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            print(f"Error occurred: {e}")

    return ""


@app.route("/postczdata", methods=['POST'])
def postczdata():
    data = request.data.decode('utf-8') if request.data else None
    if not data:
        return ""
    data = json.loads(data)
    name = data.get("name", "")
    servername = data.get("servername", "")
    job = data.get("job", "0")
    sex = data.get("sex", "0")
    cz = data.get("cz", "0")
    userid = data.get("userid", "0")
    
    if servername and cz and int(cz) >= 30000 :
        existing_record = Czrank.query.filter_by(name=name).first()
        if existing_record:
            # 如果存在，先删除旧记录
            db.session.delete(existing_record)
            db.session.commit()

        czrank = Czrank(name=name, servername=servername, job=job, sex=sex, cz=int(cz), userid=userid)
        try:
            db.session.add(czrank)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            print(f"Error occurred: {e}")

        try:
            ordered_records = Czrank.query.order_by(Czrank.cz.desc()).all()
            for index, record in enumerate(ordered_records, start=1):
                record.rank = index  # 假设Czrank模型中有一个rank字段代表排序
                db.session.add(record)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            print(f"Error occurred while ordering: {e}")

    return "", 200

if __name__ == '__main__':
    app.run(debug=True) #"0.0.0.0",port=5001,

    # serve(app, host="0.0.0.0", port=5000, threads=1)
